package com.ssyc.gsk_teacher_appraisal.activity;

import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.BqaManager;
import com.ssyc.common.manager.OnloadingMoreListener;
import com.ssyc.common.manager.SrfManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.gsk_teacher_appraisal.R;
import com.ssyc.gsk_teacher_appraisal.adapter.MainTestRvAdapter;
import com.ssyc.gsk_teacher_appraisal.bean.AppraisalTestInfo;
import com.ssyc.gsk_teacher_appraisal.bean.ClassInfo;
import com.ssyc.gsk_teacher_appraisal.utils.ClassPoputil;
import com.ssyc.gsk_teacher_appraisal.utils.ClassUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 教师端题库之测评界面
 * Created by Administrator on 2018/10/8 0008.
 */
@Route(path = "/teacherappraisal/TkTeacherAppraisalMainActivity")
public class TkTeacherAppraisalMainActivity extends BaseActivity implements SrfManager.OnPullRefreshListener, OnloadingMoreListener, View.OnClickListener {

    private ImageView ivBack;

    private ImageView ivAddTest;

    private ImageView ivChooseClass;

    private LinearLayout llContent;

    private RelativeLayout rlLoadingView;

    //所有班级的列表
    private List<ClassInfo.ListBean> classInfos;

    //记录弹出展示班级列表PopUpWindow的选中位置的值,默认第一个被选中
    private int popSelectedPos = 0;

    //标题栏的布局
    private LinearLayout llTitle;

    //是否获取班级列表数据完成的标识,没完成之前点击选择班级的弹框提示正在加载,不允许点击
    private boolean isLoadClassCompleted;

    //空视图
    private View emptyView;

    private RecyclerView rv;

    private SmartRefreshLayout srf;

    //数据列表集合
    private List<AppraisalTestInfo.ListBean> oldDatas;

    //适配器
    private MainTestRvAdapter adapter;

    //通知页面刷新的标识
    public static final String CPUPDATEPAGEDATA = "cpupdatepagedata";


    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_tk_teacher_appraisal_main;
    }

    @Override
    protected void init() {

        showContent();

        //初始化视图
        initView();

        //设置数据
        initRv();

        //请求班级数据
        httpClass();
    }

    /**
     * 初始化视图
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        ivAddTest = findViewById(R.id.iv_add_test);
        ivAddTest.setOnClickListener(this);
        llContent = findViewById(R.id.ll_content);
        rlLoadingView = findViewById(R.id.rl_loading);
        llContent.setVisibility(View.GONE);
        //标题栏
        llTitle = findViewById(R.id.ll_title);

        ivChooseClass = findViewById(R.id.iv_choose_class);
        ivChooseClass.setOnClickListener(this);

        rv = findView(R.id.rv);
        srf = findViewById(R.id.srf);
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.iv_choose_class) {
            //选择班级
            //弹出选择班级的PopUpWindow
            showClassPop();
        } else if (id == R.id.iv_add_test) {
            //选择测试套题
            UiUtils.startActivity(this, TkTeacherAppraisalChooseTestActivity.class);
        }
    }

    /**
     * 请求班级里列表数据
     */
    private void httpClass() {
        ClassUtil.httpClass(rlLoadingView, this, new ClassUtil.onSuccessListener() {
            @Override
            public void onSuccess(List<ClassInfo.ListBean> datas) {
                //回调班级数据
                classInfos = datas;

                //证明有班级
                ivChooseClass.setVisibility(View.VISIBLE);
                ivAddTest.setVisibility(View.VISIBLE);

                //初始化下拉刷新控件
                initSrf();

                if (classInfos != null && classInfos.size() != 0) {

                    //保存classnum
                    SPUtil.put(TkTeacherAppraisalMainActivity.this,
                            "classnum", classInfos.get(popSelectedPos).getClassnum());

                    //保存班级名称
                    SPUtil.put(TkTeacherAppraisalMainActivity.this,
                            "CPclassname", classInfos.get(popSelectedPos).getName());

                    //请求页面列表数据
                    httpPageData(popSelectedPos, BqaManager.NORML);

                }
            }

            @Override
            public void hasNoData() {
                //没有班级,不显示顶部的切换班级的按钮和
                ivChooseClass.setVisibility(View.INVISIBLE);
                ivAddTest.setVisibility(View.INVISIBLE);
            }
        });
    }

    /**
     * 请求页面列表数据
     */
    private void httpPageData(int popSelectedPos, int method) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "3");
        map.put("ttel", AccountUtils.getAccount(BaseApplication.context));
        map.put("classnum", classInfos.get(popSelectedPos).getClassnum());

        HttpUtils.post(HttpAdress.CPMain, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (rlLoadingView.getVisibility() == View.VISIBLE) {
                    rlLoadingView.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {

                if (rlLoadingView.getVisibility() == View.VISIBLE) {
                    rlLoadingView.setVisibility(View.GONE);
                }

                if (llContent.getVisibility() != View.VISIBLE) {
                    llContent.setVisibility(View.VISIBLE);
                }

                AppraisalTestInfo info = null;

                try {
                    info = GsonUtil.jsonToBean(response, AppraisalTestInfo.class);
                } catch (Exception e) {
                    Log.i("test", "数据解析异常");
                }

                Log.i("test", "列表json：" + response);

                if (null != info) {
                    if ("200".equals(info.getState())) {
                        //返回成功
                        List<AppraisalTestInfo.ListBean> newDatas = info.getList();

                        if (method == BqaManager.PULLREFRESH) {

                            BqaManager.updateRv(method, srf, rv, oldDatas, newDatas, adapter);
                        } else if (method == BqaManager.NORML) {
                            if (isLoadClassCompleted) {
                                BqaManager.updateRv(BqaManager.PULLREFRESH, srf, rv, oldDatas, newDatas, adapter);
                                if(newDatas.size()==0){
                                    oldDatas.clear();
                                    BqaManager.setRv(emptyView, TkTeacherAppraisalMainActivity.this, adapter, rv, TkTeacherAppraisalMainActivity.this);
                                    adapter.notifyDataSetChanged();
                                }
                            } else {
                                oldDatas.addAll(newDatas);
                                BqaManager.setRv(emptyView, TkTeacherAppraisalMainActivity.this, adapter, rv, TkTeacherAppraisalMainActivity.this);
                                //改变加载完成的标记
                                isLoadClassCompleted = true;
                            }
                        }
                    } else {
                        //返回错误
                        UiUtils.Toast("服务器返回异常,状态码是:" + info.getState(), false);
                        Log.i("test", "服务器返回异常,状态码是:" + info.getState());
                    }
                } else {
                    Log.i("test", "服务器返回数据为空");
                }
            }
        });
    }

    /**
     * 弹出展示班级列表的方法
     */
    private void showClassPop() {
        ClassPoputil.showClassPop(this, classInfos, popSelectedPos, llTitle, new ClassPoputil.onPopItemClickListener() {
            @Override
            public void onItemClick(int pos) {

                //记录当前点击条目的位置
                popSelectedPos = pos;

                //保存classnum
                SPUtil.put(TkTeacherAppraisalMainActivity.this,
                        "classnum", classInfos.get(popSelectedPos).getClassnum());
                //保存班级名称
                SPUtil.put(TkTeacherAppraisalMainActivity.this,
                        "CPclassname", classInfos.get(popSelectedPos).getName());
                //请求页面数据
                httpPageData(popSelectedPos, BqaManager.NORML);

            }
        });
    }


    /**
     * 设置列表
     */
    private void initRv() {
        oldDatas = new ArrayList<>();
        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view_coffee_bg, null);
        TextView tvMessage = emptyView.findViewById(R.id.tv_content);
        tvMessage.setText("未添加试卷");
        adapter = new MainTestRvAdapter(this, R.layout.teacher_rv_main_test, oldDatas);

    }

    /**
     * 初始化下拉刷新
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, this);
    }
    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {

    }

    /**
     * 下拉刷新
     *
     * @param refreshlayout
     */
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        httpPageData(popSelectedPos, BqaManager.PULLREFRESH);
    }


    /**
     * EventBus处理事件
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (busInfo != null && CPUPDATEPAGEDATA.equals(busInfo.msg)) {
            httpPageData(popSelectedPos, BqaManager.PULLREFRESH);
        }
    }
}
